package com.example.iqiyitest.hztvpaysdk;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Base64;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public abstract class BasePayListenerActivity extends Activity {

    private static final String TAG = "BasePayListenerActivity";

    private Gson mGson = new Gson();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);	
        String payMsgJsonStr = getIntent().getStringExtra("KEY_PAY_MESSAGE");
        if (TextUtils.isEmpty(payMsgJsonStr)) {
            Log.e(TAG, "Failed to parse pay message from intent!");
            finish();
            return;
        }
        PushMessage payMsg;
        try {
            payMsg = mGson.fromJson(payMsgJsonStr, PushMessage.class);
        } catch (JsonSyntaxException e) {
            Log.e(TAG, "Wrong json format for pay message: " + payMsgJsonStr);
            e.printStackTrace();
            finish();
            return;
        }
        String plainData = decryData(payMsg.postdata);
        if (!checkSign(plainData, payMsg.sign)) {
            Log.e(TAG, "Sign verification not passed for the push message!");
            return;
        }
        onPayResult(mGson.fromJson(plainData, PushMessage.Data.class));
        if (noViews()) {
            finish();
            return;
        }
    }

    /**
     * 子类需要重写该方法来处理支付结果。
     * @param data
     */
    protected abstract void onPayResult(PushMessage.Data data);

    /**
     * 默认情况下继承自{@link BasePayListenerActivity}的activity是没有界面的，如果子类想要显示自己的界面可以
     * 重写该方法，并返回false。
     * @return
     */
    protected boolean noViews() {
        return true;
    }


    private String decryData(String encryData) {
        try {
            return new String(RC4Factory.decry_RC4_byte(Base64.decode(encryData, Base64.NO_WRAP), HztvPayUtil.getPubKey()), "utf-8");
        } catch (UnsupportedEncodingException e) { // Never happen
            e.printStackTrace();
            return null;
        }
    }

    private boolean checkSign(String plainData, String sign) {
        String mySign = null;
        try {
            mySign = SecurityUtil.bytes2Hex(MessageDigest.getInstance("MD5").digest((plainData + HztvPayUtil.getPriKey()).getBytes("utf-8")));
        } catch (NoSuchAlgorithmException e) { // Never happen
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) { // Never happen
            e.printStackTrace();
        }
        return sign.equals(mySign);
    }
}
